<template>
  <div class="app-container">
    <el-form :model="queryParams">
      <el-row class="query-wrapper">
        <el-select v-model="queryParams.vesselName" filterable clearable  placeholder="Vessel" style="width:180px"
          @change="selectVessel">
          <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
          </el-option>
        </el-select>
        &nbsp;
        <el-select v-model="queryParams.voyageNo" filterable clearable allow-create placeholder="Voyage" style="width:100px"
          @change="selectVoyage">
          <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
          </el-option>
        </el-select>
        &nbsp; 
        <el-select v-model="queryParams.pol" filterable clearable allow-create placeholder="POL" style="width:150px">
          <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pols">
          </el-option>
        </el-select>
        &nbsp; 
        <el-select v-model="queryParams.pod" filterable clearable allow-create placeholder="POD" style="width:150px">
          <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pods">
          </el-option>
        </el-select>
        &nbsp;
        <el-select v-model="queryParams.payer" filterable clearable allow-create placeholder="Client">
          <el-option :key="item.fullName" :label="item.fullName" :value="item.fullName" v-for="item in clients">
          </el-option>
        </el-select>   
        &nbsp;
        <el-select v-model="queryParams.brand" filterable clearable allow-create placeholder="Brand" style="width:130px">
          <el-option :key="item.name" :label="item.name" :value="item.name" v-for="item in brands">
          </el-option>
        </el-select>
        &nbsp;
        &nbsp;
        <el-button type="primary"  icon="search"  @click="search">Search</el-button>
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
		 </el-row> 
		  <el-row class="query-wrapper" style="margin-top: 20px;margin-bottom: 10px;"> 
        <el-button type="primary" plain  @click="batchSetting">Group Handling</el-button>
        &nbsp;&nbsp;
        <el-button type="warning" :disabled="listData.length==0" plain @click="exportHandle ">Export Settlement List</el-button>&nbsp;

      </el-row> 
    </el-form>
  </div> 
      <el-table
        ref="tableRef"
        v-loading="loading"
        stripe
        :data="listData"
        style="width: 100%" 
        :cell-style="{textAlign:'center'}"
        :show-overflow-tooltip="true"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
      >        
      <el-table-column type="selection" :selectable="selectable" width="55" /> 
      <el-table-column prop="bookingNo" label="Booking No" width="110" fixed="left"/> 
      <el-table-column prop="payer" label="Freight Payable Party" width="200"/> 
    
      <el-table-column prop="pol" label="POL" width="100" show-overflow-tooltip/>
      <el-table-column prop="pod" label="POD"  width="100" show-overflow-tooltip/>
      <el-table-column prop="unitCbm" label="Decleared CBM"  width="120" show-overflow-tooltip/>
      <el-table-column prop="measureUnitCbm" label="Measured CBM"  width="120" show-overflow-tooltip/>
      <el-table-column prop="measureType" :label="'Dimension'+'\n'+'To Apply'" width="130" align="center">
        <template #default="scope">
          <div @click="editClickEvent(scope.row)" style="width:100%;cursor:pointer" :class="scope.row.measureType==2?'measure-red':''" v-if="scope.row.id !=null">&nbsp;{{ cbmTypes[scope.row.measureType] }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="freightRate" label="Freight Rate" width="120" >
        <template #default="scope">
          <div @click="editClickEvent(scope.row)" style="width:100%;cursor:pointer" v-if="scope.row.id !=null">&nbsp;{{ scope.row.freightRate}}</div>
        </template>
      </el-table-column>
   
      <el-table-column prop="shippingTerms" label="Freight Rate Term" width="130" >
        <template #default="scope">
          <div @click="editClickEvent(scope.row)" v-if="scope.row.id !=null">&nbsp;{{ scope.row.shippingTerms   }}</div>
        </template>
      </el-table-column>  

      <el-table-column prop="brand" label="Brand" width="100" />
      <el-table-column prop="model" label="Model"  width="100" /> 
      <el-table-column prop="totalUnits" label="Total Units" width="120" />
      <el-table-column prop="settleLength" label="Length(m)" width="90" /> 
      <el-table-column prop="settleWidth" label="Width(m)" width="90" />
      <el-table-column prop="settleHeight" label="Height(m)" width="90" />
      <el-table-column prop="settleVolume" label="Unit Cbm" width="90" />
      <el-table-column prop="settleTotalVolume" :label="'Total Volume'+'\n'+'（cbm）'" width="120" />
      <el-table-column  prop="unitWeight"  label="Unit Weight"  width="150"  /> 
      
      <el-table-column prop="totalWeight" :label="'Total Weight'+'\n'+'(kg)'" width="120" />  
      <el-table-column  prop="cargoDesc" label="Cargo Description"  width="200"/>                 
      <el-table-column prop="blNo" label="B/L No" width="150" fixed="right"/>         
        <el-table-column label="Operation" width="120" fixed="right"  v-hasPermi="['freightedTable:edit']">
          <template #default="scope">
            <span class="btn-primary" v-if="scope.row.id != null && scope.row.spareLocation !='Inside Vehicle'" @click="editClickEvent(scope.row)">{{
              $t("ship.button.edit")
            }}</span>
         
          </template>
        </el-table-column>
      </el-table>
      <pagination
      v-show="total > 0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="pageQuery"
      style="float: right"
    /> 
    <!-- </div>
  </div> -->

  <el-dialog
    class="add_dialog"
    destroy-on-close
    draggable
    :width="500"
    :title="dialogTitle"
    v-model="dialogFormVisible"
  >
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="24">
          <el-form-item label="Booking No." label-width="220px">
             {{ formParam.bookingNo }}
          </el-form-item>
        </el-col>
      </el-row>  
      <el-row>
        <el-col :span="24">
          <el-form-item label="Choose Dimension" label-width="220px" required>
            <el-select v-model="formParam.measureType"  :disabled="!measureTypeEditable">
              <el-option
                :key="index"
                :label="item"
                :value="index"
                :disabled="disableStatus.includes(index) " 
                v-for="(item, index) in cbmTypes"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>  
      <el-row>
        <el-col :span="24">
          <el-form-item label="Freight Rate" label-width="220px">
            <el-input-number v-model="formParam.freightRate" @blur="setRateType"/>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="Total Freight" label-width="120px">
            {{ formParam.totalFreight }} 
          </el-form-item>
        </el-col> -->
      </el-row>  
      <el-row>
        <el-col :span="24">
          <el-form-item label="Freight Rate Term" label-width="220px" prop="shippingTerms">  
                <el-select v-model="formParam.shippingTerms" filterable>
                  <el-option v-for="item in freight_rate_term" :key="item.label" :label="item.label" :value="item.label" />
              </el-select>  
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
        }}</el-button> 
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
        }}</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
    class="add_dialog"
    destroy-on-close
    draggable
    :width="500"
    :title="dialogTitle"
    v-model="dialogFormVisible1"
  >
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="Booking No." label-width="120px">
             {{ formParam.bookingNo }}
          </el-form-item>
        </el-col>
      </el-row>   -->
      <el-row>
        <el-col :span="20">
          <el-form-item label="Choose Volume" label-width="120px" required>
            <el-select v-model="formParam.measureType"  :disabled="!measureTypeEditable">
              <el-option
                :key="index"
                :label="item"
                :value="index"
                :disabled="disableStatus.includes(index) " 
                v-for="(item, index) in cbmTypes"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>  
      <el-row>
        <el-col :span="20">
          <el-form-item label="Freight Rate" label-width="120px" required>
            <el-input-number v-model="formParam.freightRate" @blur="setRateType"/>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="Total Freight" label-width="120px">
            {{ formParam.totalFreight }} 
          </el-form-item>
        </el-col> -->
      </el-row>  
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="Freight Rate Term" label-width="120px" prop="shippingTerms">  
                <el-select v-model="formParam.shippingTerms" filterable>
                  <el-option v-for="item in freight_rate_term" :key="item.label" :label="item.label" :value="item.label" />
              </el-select>  
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">{{
          $t("ship.button.cancel")
        }}</el-button> 
        <el-button type="primary" @click="submitBatchForm">{{
          $t("ship.button.submit")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup name="loadedList">
// @ts-nocheck
import { ref, onMounted, reactive, watch } from "vue";
import service from "@/utils/request";
import { ElNotification, ElMessageBox,ElMessage } from "element-plus";
import { useTableDrag } from '@/hooks/useHooks' 
import { downloadFile } from "@/utils/downloadFile";
const { tableRef, proxy } = useTableDrag();
const router = useRouter();
const lashHookStatus = [ "No","Yes"];
const custForm = ref();
const dialogTitle = ref("");
let clients = reactive([]);
const loading = ref(false)
const initForm = {
  id: null, 
  brand: null,
  bookingNo:null,
  cargoType: null,
  vesselName: null,
  voyageNo: null,
  measureType:0,
  freightRate: null,
  shippingTerms:null
};

const formParam = reactive(Object.assign({}, initForm));
const multipleSelection = ref<User[]>([])
const total = ref(0);

const rules = ref({
  shippingTerms: [{ required: true, message: "freight rate term can't be blank" }],
  freightRate: [{ required: true, message: "freight rate can't be blank" }],
}); 

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  status: 1,
  vesselNo: null,
  voyageNo: null,
  orderByColumn: undefined,
  isAsc: undefined,
});

let carriers = ref([] as any);
let vessels = reactive([] as any);
let voyages = reactive([] as any);
let pols = ref([] as any);
let pods = ref([] as any); 
let recordData = ref([] as any);
let brands = reactive([])
let disableStatus =[2]
const ids = ref([]);
let freight_rate_term = reactive([])
let freightRules = reactive([])
const listData = ref([]);
const refreshTable = async () => {
  loading.value = true
  let result = await service.get("/shipping/freighted/withWeight", {
    params: queryParams,
  });
  listData.value = result.data; 
  loading.value = false
  //total.value = result.total;
};
const resetQuery = (data) => {
    Object.assign(queryParams, data)
    listData.value = []
}
const dialogFormVisible = ref(false);
const measureTypeEditable = ref(true)
const cbmTypes = ["Compare Size", "Declared","Measured"];
const dialogFormVisible1 = ref(false);
const editClickEvent = (row: any) => {
  dialogTitle.value = "Settement Parameter";
  dialogFormVisible.value = true;
  Object.keys(initForm).forEach((k) => (formParam[k] = row[k])); 
  let item = freightRules.find(n=>{return n.vesselName== formParam.vesselName && n.voyageNo==formParam.voyageNo && n.brand == formParam.brand})
  measureTypeEditable.value = true
  if(item){
    formParam.measureType = 1
    measureTypeEditable.value = false
  }
  if(formParam.measureType == null){
    formParam.measureType = 0
    measureTypeEditable.value = true
  }  
};

const batchSetting = ()=>{
  dialogTitle.value = "Group Handling";
  dialogFormVisible1.value = true;
}

const exportHandle = (row)=>{
  let title = 'AICC_Settlement_List_' + queryParams.vesselName +"_"+ queryParams.voyageNo + ".xlsx"
  downloadFile("/shipping/freighted/exportSettlementList", queryParams, title);
}

 
const handleCbmType = async (row) => {
  // if (formParam.measureType == 1) {
  //   let params = { model: row.model,brand:row.brand,cargoType:row.cargoType };
  //   let result = await service.get("/shipping/vehicleModel/getInfo", params);
  //   if (result && result.data) {
  //     row.unitWeight = result.data.measureWeight;
  //     formParam.unitWidth = result.data.measureWidth;
  //     formParam.unitHeight = result.data.measureHeight;
  //     formParam.unitLength = result.data.measureLength;
  //   }
  // }
};

const setRateType = async (row) => {
  if (formParam.rateType == 0) {
    formParam.totalFreight = (
      formParam.freightRate *
      formParam.totalUnits *
      formParam.unitHeight *
      formParam.unitHeight *
      formParam.unitLength
    ).toFixed(2);
  } else if (formParam.rateType == 1) {
    let value1:number = (
      formParam.freightRate *
      formParam.totalUnits *
      formParam.unitHeight *
      formParam.unitHeight *
      formParam.unitLength
    );
    let value2:number = (formParam.totalFreight =
      formParam.freightRate * formParam.totalUnits * formParam.unitWeight);

    formParam.totalFreight = value1 > value2 ?   value1.toFixed(2) : value2.toFixed(2);
  }
};

const submitBatchForm = async()=>{
  const ids = [];
  for (const rs of multipleSelection.value) {
      ids.push (rs.id)
  }

  if(ids.length <=1){
    // @ts-ignore
    ElNotification.warning({ title: "Prompt information", message: "choose data to batch setting!", position: "bottom-right" });
    return;
  }
 

  if(formParam.freightRate == null){
    ElNotification.warning({ title: "Prompt information", message: "please setting the freight rate!", position: "bottom-right" });
   return;

  }
  await service.put(`shipping/freighted/batchUpdateFreightRate/`+ids,formParam);
  ElNotification.success({
    title: "Prompt information",
    message: "batch set Freight Rate success!",
    position: "bottom-right"
  });
  refreshTable() 
}

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => {
  // @ts-ignore
  custForm.value.validate(async (valid) => {
    if (!valid) {
      // @ts-ignore
      ElNotification.warning({
        title: "Prompt information",
        message: "verification not success！",
        position: "bottom-right",
      });
      return;
    }

    await service.put("shipping/freighted/updateFreightRate", formParam);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right",
    });
    dialogFormVisible.value = false;
    search();
  });
};

const pageQuery = async (e) => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = async () => { 
  loading.value = true
  let result = await service.get("/shipping/freighted/withWeight", {
    params: queryParams,
  });
  listData.value = result.data;
  loading.value = false
  //total.value = result.total
};

const selectVessel = async () => {
  //@ts-ignore
  queryParams.voyageNo = null;
  queryParams.pol = null;
  queryParams.pod = null;
  voyages = [];
  pods = [];
  pols = [];
  let item = vessels.find(n => n.vesselName == queryParams.vesselName)
  voyages = item.schedules
}

const selectVoyage = async () => {
  queryParams.pol = null;
  queryParams.pod = null;
  //@ts-ignore
  let item = voyages.find(n => n.voyageNo == queryParams.voyageNo)
  pods = item.pods
  pols = item.pols
}

const uploadFile = async (event) => {
  if (event.target == null || event.target.files[0] == null) {
    return;
  }
  const formData = new FormData();
  formData.append("file", event.target.files[0]);
  await service["post"]("shipping/booking/uploadFile", formData);
};

const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

const handleSubmit = ()=>{
  if (listData.value.length <= 0) {
    ElNotification.warning({
      title: "Prompt information",
      message: "no data to submit！",
      position: "bottom-right"
    });
    return;
  }

  ElMessageBox.confirm("Confirm to send the declare information to approve？", "Confirmation Information", {
    type: "warning"
  }).then(async () => {
    let params = { bookings: listData.value };
    await service.post(`shipping/freighted/submit`, params);
    ElNotification.success({
      title: "Prompt information",
      message: "submit the data success!",
      position: "bottom-right"
    });
    //await service.delete(`shipping/booking/${id}`);
  });
}

const removeClickEvent = (id) => {
  ElMessageBox.confirm(
    "Confirm to Remove the data？",
    "Confirmation Information",
    {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }
  ).then(async () => {
    await service.delete(`shipping/booking/${id}`);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Delete successfully!",
      position: "bottom-right",
    });
  });
};
/////////////////////////////////////////////////// 

const selectable = (row: User) => (row.id != null)
 
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val 
}


onMounted(async () => {
  let result = await service.get("/shipping/schedule/getAllSchedule");
  if (result) {
    vessels = result.data;
  }
  result = await service.get("/shipping/brand/list");
  if (result) {
    brands = result.data;
  }
  const res = await proxy.useDict("freight_rate_term");
  freight_rate_term = res.freight_rate_term 
  service.get("/shipping/freightRule/list", {params: queryParams}).then(result=>{
    freightRules = result.data
  })
  
  result = await service.get("/shipping/client/list");
  if (result) {
    clients = result.data
  }
  //refreshTable();
});
</script>
<style lang="scss" scoped>
 .add_dialog {
  width: 500px !important;
  max-width: 95vw;

  .el-select {
    width: 100%;
  }

  element.style {
    width: 4000;
  }

  .el-icon-upload {
    font-size: 2rem;
    cursor: pointer;
  }
}
.el-table__expand-column .cell {
  display: none;
}

.c-expand {
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  cursor: pointer;
  width: 100%;
  height: 100%;
}

.c-expand i {
  font-size: 16px;
}

.c-expand i.expand {
  font-size: 16px;
  transform: rotate(90deg);
  transition: all 0.25s;
}

.el-table {
    thead {
      .cell {
        white-space: pre-line !important;
      }
    }
  }

.table-boxs {
  width: 100%;
  overflow-x: auto;
}

.ipx {
  width: 100%;
  text-align: center;
}

.table-box {
  width: 4000px;
}

.block2 {
min-height: 100px;
.el-row {
 margin:10px 10px 20px 25px;
}
}
.measure-red{
  color: red;
}
</style>